package com.ze.familyday.familyphotoframe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.ze.commontool.CustomDialog;
import com.ze.commontool.LoadImageMgr;
import com.ze.commontool.NetHelper;
import com.ze.commontool.PublicInfo;
import com.ze.commontool.SoundPlayStop;
import com.ze.commontool.ToastUtil;
import com.ze.commontool.LoadImageMgr.ImageCallBack;
import com.ze.commontool.SoundPlayer;
import com.ze.commontool.UpdateTools;
import com.ze.commontool.UpdateTools.DownloadCallback;
import com.ze.familyday.familyphotoframe.R;
import com.ze.familydayverpm.adapter.SpaceViewPagerAdapter;
import com.ze.familydayverpm.userinfo.Componet;
import com.ze.familydayverpm.userinfo.UserInfoManager;
import com.ze.model.DataModel;
import com.ze.model.ModelDataMgr;
import com.ze.model.PhotoModel;
import com.ze.model.PhotoModel.PicInfo;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.ContactsContract.Contacts.Data;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View.OnTouchListener;
import android.view.MotionEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PhotoFrameActivity extends Activity {
	
	public static RelativeLayout mLevelRl;
	public static TextView mLevelTv;
	private RelativeLayout tipsRl;
	private boolean soundTipsRlFlag;
	public static Button playSoundBtn;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	
	/**
	 *  2013.11.3 
	 *  @ze
	 *  修改控件
	 */
	private 	ViewPager 						mViewPager;
	private 	SpaceViewPagerAdapter 		mviewAdapter;
	/*********************/
	
	
	public final static String TAG = "PhotoFrameActivity";
	public final static String MYTAG = "mousetest";
	/**
	 * 展示的图片
	 */
//	private ImageView img_1;
	/**
	 * 默认图片 pic_default
	 */
//	private ImageView img_2;
	/**
	 * 图片信息
	 */
	AlertDialog 	mProgressDialog;
	View 			view_progress;
	TextView		tv_progress;
	ImageButton 	btn_progress;
	//JSONArray array ;
	List<JSONObject> mListJSON;
	
	int currentPage = 0;
	public static PhotoFrameActivity instance;
	/**
	 * 退出按钮
	 */
	private View logoutView;
	private TextView txt_logout;
	/**
	 * 收藏按钮
	 */
	private Button love;
	private TextView txt_love;
	private View menuView;
	/**
	 * 父控件
	 */
	private View photoFrameView;	// img 父控件
	// 整个界面的父控件
	private Animation menuInAnimation;
	private Animation menuOutAnimation;
	
	private View playAll;
	private TextView txt_playAll;
	private View playLove;
	private TextView txt_playLove;
	//private View wifiView;
	//private TextView txt_wifi;
	
	private View playMine;
	private TextView txt_playMine;
	
//	private AnimationSet deleteOutAnimation;
	
//	private View 			layout_info_img;
	private int 				model;
	private boolean 	uselocal;
	boolean isLogin = true;
	private String 		m_auth;
	
	private   int  pageCount = 0;  // 计算当前数据包括了几页
	private 		BroadcastReceiver receiver ;
	/**
	 * 背景图片
	 */
//	View  			imgLoadingView;
	/**
	 * 连击5下进入debugmodel
	 */
	View 			checkButtonView;
	Context mContext;
	/**
	 * 电量提示对话框
	 */
	Dialog batteryDialog;
	/**
	 * 电量提示框文字
	 */
	TextView BD_notice;
	/**
	 * 电量提示框按钮
	 */
	Button BD_btn;
	
	/**
	 * 充电状态
	 */
	int currentLevel = -1;
	Dialog loginDialog;
	
	LayoutInflater inflater;
	/**
	 * 自定义退出对话框
	 */
	Dialog exitDialog;
	/**
	 * 退出对话框的取消按钮
	 */
	Button ED_cancelBtn;
	/**
	 * 退出对话框的确定按钮
	 */
	Button ED_OKBtn;
	/**
	 * 退出对话框的提示
	 */
	TextView ED_notice;
	
	//多图排版
	public final static int [] picLayoutid = new int[]{R.layout.pic_one, R.layout.pic_two
		,R.layout.pic_three, R.layout.pic_four, R.layout.pic_five, R.layout.pic_six
		,R.layout.pic_seven, R.layout.pic_eight, R.layout.pic_nine};
	public final static int [] imgid = new int[]{R.id.img1, R.id.img2, R.id.img3, 
		R.id.img4, R.id.img5, R.id.img6, R.id.img7, R.id.img8, R.id.img9};
	public View picView;
	public ImageView [] img = new ImageView[9];
	
	int testModel = 1;
	private Button mPlaySoundBtn;
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		Log.v("cube", "onSaveInstanceState");
		super.onSaveInstanceState(outState);
		((FamilyDayVerPMApplication)getApplication()).mList = mListJSON;
		outState.putInt("pageCount", pageCount);
		outState.putSerializable("arrayList", arrayList);
		outState.putInt("checkcount", checkcount);
		outState.putInt("currentPage", currentPage);
		outState.putBoolean("firstShowFlag", firstShowFlag);
		outState.putBoolean("initFlag", initFlag);
		outState.putBoolean("isDestryoed", isDestryod);
//		outState.putBoolean("isLoadingPic", isLoadingPic);
		outState.putInt("loadImgCount", loadImgCount);
		outState.putBoolean("loadListTaskFlag", loadListTaskFlag);
		outState.putString("uid", mUidString);
		outState.putBoolean("menuShowFlag", muneShowFlag);
		outState.putInt("switchPlayModel", switchPlayModel);
		outState.putBoolean("uselocal", uselocal);
		outState.putBoolean("isLogin", isLogin);
		outState.putBoolean("playstop", play_stop);
		outState.putBoolean("onsave", true);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate");
		setContentView(R.layout.activity_frame);
		
		// 清空缓存文件，如果此次更新与缓存文件无关，则可注释
		// 如有关，需要在函数下修改清空标志
		UpdateTools.installClear(this);
		
		
		//初始化变量 
		mContext = this;
		inflater = LayoutInflater.from(mContext);//end
		
		playSoundBtn = (Button) findViewById(R.id.playSoundBtn);
		playSoundBtn.setOnClickListener(buttonClickListener);
		playSoundBtn.setSelected(false);
		tipsRl = (RelativeLayout) findViewById(R.id.tipsRl);
		tipsRl.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (tipsRl.getVisibility() == View.VISIBLE) {
					tipsRl.setVisibility(View.GONE);
				}
				return false;
			}
		});
		SharedPreferences soundPreferences = 
				getSharedPreferences("update.config", Activity.MODE_WORLD_READABLE);
		soundTipsRlFlag = soundPreferences.getBoolean("soundTipsRl", false);
		mLevelRl = (RelativeLayout) findViewById(R.id.levelRl);
		mLevelTv = (TextView) findViewById(R.id.levelTv);
		mLevelRl.setVisibility(View.INVISIBLE);
		
		uselocal = getIntent().getBooleanExtra("uselocal",false);
		//初始化电量提示框
		if (batteryDialog == null){
			batteryDialog = new CustomDialog(mContext, 410, 250, R.layout.dialog_notice_layout,
					R.style.FullHeightDialog);
			batteryDialog.setCanceledOnTouchOutside(true);
			View view = getLayoutInflater().inflate(R.layout.dialog_notice_layout, null);
			BD_notice = (TextView) view.findViewById(R.id.dn_notice);
			BD_notice.setText("charging tips");
			BD_btn = (Button) view.findViewById(R.id.dn_cancel);
			BD_btn.setText("OK");
			BD_btn.setOnClickListener(buttonClickListener);
			((Button) view.findViewById(R.id.dn_OK)).setVisibility(View.GONE);
			batteryDialog.setContentView(view);
		}
		//初始化自定义退出框
		if (exitDialog == null && !uselocal) {
			exitDialog = new CustomDialog(mContext, 410, 250, R.layout.dialog_notice_layout,
					R.style.FullHeightDialog);
			exitDialog.setCanceledOnTouchOutside(false);
			View view = getLayoutInflater().inflate(R.layout.dialog_notice_layout, null);
			ED_cancelBtn = (Button) view.findViewById(R.id.dn_cancel);
			ED_cancelBtn.setText("cancel");
			ED_cancelBtn.setOnClickListener(buttonClickListener);
			ED_OKBtn = (Button) view.findViewById(R.id.dn_OK);
			ED_OKBtn.setText("OK");
			ED_OKBtn.setOnClickListener(buttonClickListener);
			ED_notice = (TextView) view.findViewById(R.id.dn_notice);
			ED_notice.setText("logout?");
			exitDialog.setContentView(view);
			//exitDialog.show();
		} else if (exitDialog == null && uselocal) {
			exitDialog = new CustomDialog(mContext, 410, 250, R.layout.dialog_notice_layout,
					R.style.FullHeightDialog);
			exitDialog.setCanceledOnTouchOutside(false);
			View view = getLayoutInflater().inflate(R.layout.dialog_notice_layout, null);
			ED_cancelBtn = (Button) view.findViewById(R.id.dn_cancel);
			ED_cancelBtn.setText("login");
			ED_cancelBtn.setOnClickListener(buttonClickListener);
			ED_OKBtn = (Button) view.findViewById(R.id.dn_OK);
			ED_OKBtn.setText("continue");
			ED_OKBtn.setOnClickListener(buttonClickListener);
			ED_notice = (TextView) view.findViewById(R.id.dn_notice);
			ED_notice.setText("please login");
			exitDialog.setContentView(view);
		}
		//判断是否登录
		//isLogin = getIntent().getBooleanExtra("isLogin", true);
		if( uselocal )
		{
			m_auth = null;
		}else
		{
			if( UserInfoManager.getInstance(this).getItem("m_auth") != null )
			{
				m_auth = UserInfoManager.getInstance(this).getItem("m_auth").getValue();
				//By mouse 
				//此处传入m_auth的值  并且启动服务
				PullImageService.m_auth = m_auth;
				Intent stopIntent = new Intent(mContext, PullImageService.class);
				mContext.stopService(stopIntent);
				Intent startIntent = new Intent(mContext, PullImageService.class);
				mContext.startService(startIntent);
				Log.v(PullImageService.TAG, "启动服务");
				
			}
		}
		photoFrameView = findViewById(R.id.pic_content_layout);
		photoFrameView.setOnClickListener(buttonClickListener);
		checkButtonView = findViewById(R.id.photoframe_check);
		checkButtonView.setOnClickListener(buttonClickListener);
		model = getIntent().getIntExtra("model", PLAYING_ALL);
//		stopView = (Button) findViewById(R.id.photoframe_stop);
		logoutView = findViewById(R.id.photoframe_logout);
		txt_logout = (TextView) findViewById(R.id.txt_logout);
		love = (Button) findViewById(R.id.photoframe_love);
		txt_love = (TextView) findViewById(R.id.txt_love);
		playAll = findViewById(R.id.photoframe_play_all);
		txt_playAll = (TextView) findViewById(R.id.txt_play_all);
		playLove = findViewById(R.id.photoframe_play_love);
		txt_playLove = (TextView) findViewById(R.id.txt_play_love);
		//增加我的图标
		playMine =findViewById(R.id.photoframe_play_mine);
		txt_playMine = (TextView) findViewById(R.id.txt_play_mine);
		
		playAll.setOnClickListener(buttonClickListener);
		txt_playAll.setOnClickListener(buttonClickListener);
		playLove.setOnClickListener(buttonClickListener);
		txt_playLove.setOnClickListener(buttonClickListener);
		playMine.setOnClickListener(buttonClickListener);
		txt_playMine.setOnClickListener(buttonClickListener);
		if( model == PLAYING_ALL )
		{
			playAll.setSelected(true);
		}else if (model == PLAYING_LOVE)
		{
			playLove.setSelected(true);
		} else
		{
			playMine.setSelected(true);
		}
		logoutView.setOnClickListener(buttonClickListener);
		txt_logout.setOnClickListener(buttonClickListener);
		love.setOnClickListener(buttonClickListener);
		txt_love.setOnClickListener(buttonClickListener);
		menuView = findViewById(R.id.photoframe_menu_layout);
		
		PublicInfo.SCREEN_W = getWindowManager().getDefaultDisplay().getWidth();
		PublicInfo.SCREEN_H = getWindowManager().getDefaultDisplay().getHeight();
		//img_2.setVisibility(View.INVISIBLE);
		arrayList = new ArrayList<DataModel>();
		//array = new JSONArray();
		mListJSON = new ArrayList<JSONObject>();
		 // viewpager
        mViewPager = (ViewPager)findViewById(R.id.photoshowViewPager);
		
		mviewAdapter = new SpaceViewPagerAdapter(this, mListJSON);
		mViewPager.setAdapter(mviewAdapter);
		mViewPager.setOnClickListener(buttonClickListener);
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				onpage(arg0);
				
				if (mLevelRl.getVisibility() == View.VISIBLE) {
					mLevelRl.setVisibility(View.INVISIBLE);
				}
				JSONObject object = mListJSON.get(arg0);
				try {
					if (!object.isNull("soundurl") && !object.getString("soundurl").equals("")) {
						playSoundBtn.setVisibility(View.VISIBLE);
					}else {
						playSoundBtn.setVisibility(View.INVISIBLE);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
		indexAnimation = new AlphaAnimation(0.0f, 1.0f);
		indexAnimation.setAnimationListener(animationListener);
		indexAnimation.setDuration(500);
		dismissAnimation = new AlphaAnimation(1.0f, 0.0f);
		dismissAnimation.setAnimationListener(animationListener);
		dismissAnimation.setDuration(500);
		slideLeftAnimation = new TranslateAnimation
		(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,-1.0f, Animation.RELATIVE_TO_SELF, 0.0f, 
				Animation.RELATIVE_TO_PARENT,0.0f) ;
		slideLeftAnimation.setDuration(500);
		slideLeftAnimation.setAnimationListener(animationListener);
		slideRightAnimation = new TranslateAnimation
		(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,1.0f, Animation.RELATIVE_TO_SELF, 0.0f, 
				Animation.RELATIVE_TO_PARENT,0.0f) ;
		slideRightAnimation.setDuration(500);
		slideRightAnimation.setAnimationListener(animationListener);
		instance = this;
		menuInAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,0.0f, 
				Animation.RELATIVE_TO_SELF, -1.0f, 
				Animation.RELATIVE_TO_SELF,0.0f);
		menuInAnimation.setAnimationListener(animationListener);
		menuInAnimation.setDuration(200);
		menuInAnimation.setFillEnabled(true);
		menuInAnimation.setFillAfter(true);
		menuOutAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,0.0f, 
				Animation.RELATIVE_TO_SELF, 0.0f, 
				Animation.RELATIVE_TO_SELF,-1.0f);
		menuOutAnimation.setAnimationListener(animationListener);
		menuOutAnimation.setDuration(200);
		menuOutAnimation.setFillEnabled(true);
		menuOutAnimation.setFillAfter(true);
//		deleteOutAnimation = new AnimationSet(true);
//		deleteOutAnimation.addAnimation(new ScaleAnimation(1.0f, 0.1f, 1.0f, 0.1f, 
//				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) );
//		deleteOutAnimation.addAnimation(new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_PARENT,0.5f, Animation.RELATIVE_TO_SELF, 0.0f, 
//				Animation.RELATIVE_TO_PARENT,-1.0f) );
//		deleteOutAnimation.setDuration(500);
//		deleteOutAnimation.setAnimationListener(deleteAnimationListener);
		
		view_progress = getLayoutInflater().inflate(R.layout.define_progress_dialog, null);
		tv_progress = (TextView)view_progress.findViewById(R.id.dpd_tv);
		btn_progress = (ImageButton)view_progress.findViewById(R.id.dpd_btn);
		btn_progress.setOnClickListener(buttonClickListener);
		
		loginDialog = new Dialog(mContext, R.style.FullHeightDialog);
		loginDialog.setContentView(view_progress);
		loginDialog.setCanceledOnTouchOutside(false);
		
		
		if ( this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE )
		{
			isLandscape = true;
		}else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
		{
			isLandscape = false;
		}
		if (savedInstanceState != null && savedInstanceState.getBoolean("onsave", false)) {
			Log.v("mouse", "转屏");
			changeScreenInit(savedInstanceState);
			mViewPager.setVisibility(View.INVISIBLE);
			mviewAdapter = new SpaceViewPagerAdapter(this, mListJSON);
			mViewPager.setAdapter(mviewAdapter);
			onpage(currentPage);
//			showNext(currentPage,0);
//			judgeNext(PHOTO_SHOW_TIME);
		}else
		{
			//getLocalListTask();
			//uselocal = true;
			if (!uselocal){
				loadListTask(true, model);
			} else {
				getLocalListTask();
			}
//			judgeNext(500);
		}
		
		receiver = new WifiReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		registerReceiver(receiver, filter);
		flagReceive = true;
		
		// 锁定wifi不休眠
		 WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
         wifiLock = manager.createWifiLock("SwiFTP");
         wifiLock.setReferenceCounted(false);
         wifiLock.acquire();
         
         pm = (PowerManager)getSystemService(POWER_SERVICE); 
         mWakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.SCREEN_DIM_WAKE_LOCK, "SimpleTimer");
         wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
          
         // 网络线程
         networkThread = new HandlerThread("network");
         networkThread.start();
         networkHandler = new Handler(networkThread.getLooper());
         pushRunnableList = new ArrayList<Runnable>();
         
         //注册监测wifi广播 By mouse
         IntentFilter wififilter = new IntentFilter();
         wififilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         wififilter.addAction(Intent.ACTION_BATTERY_CHANGED);
         registerReceiver(wifiReceiver, wififilter);
         
         initPlayHandle();
	}
	
	
	
	boolean testFlag = true;
	
    public boolean flagReceive = false;
	
	
	ArrayList<Runnable> pushRunnableList = null;
    HandlerThread networkThread;
    Handler networkHandler;
    PowerManager pm;
    WakeLock wl;
    WifiLock wifiLock;
//	 KeyguardLock keyguardLock = null;
    WakeLock mWakeLock = null;
    boolean isLandscape = true;
    
	public void changeScreenInit(Bundle saveBundle)  
	{
		mListJSON = ((FamilyDayVerPMApplication)getApplication()).mList;
		pageCount = saveBundle.getInt("pageCount");
		arrayList = (ArrayList<DataModel>) saveBundle.getSerializable("arrayList");
		checkcount = saveBundle.getInt("checkcount");
		currentPage = saveBundle.getInt("currentPage");
		firstShowFlag	 = saveBundle.getBoolean("firstShowFlag");
		initFlag	 = saveBundle.getBoolean("initFlag");
		if( initFlag )
		{
//			imgLoadingView.setVisibility(View.INVISIBLE);
//			layout_info_img.setVisibility(View.VISIBLE);
		}
		isDestryod	 = saveBundle.getBoolean("isDestryoed");
//		isLoadingPic	 = saveBundle.getBoolean("isLoadingPic");
		loadImgCount = saveBundle.getInt("loadImgCount");
		loadListTaskFlag	 = saveBundle.getBoolean("loadListTaskFlag");
		mUidString	= saveBundle.getString("uid");
		muneShowFlag = saveBundle.getBoolean("menuShowFlag");
		play_stop = saveBundle.getBoolean("playstop");
		if( play_stop )
		{
			menuView.setVisibility(View.VISIBLE);
			menuView.startAnimation(menuInAnimation);
		}
		switchPlayModel = saveBundle.getInt("switchPlayModel");
		uselocal = saveBundle.getBoolean("uselocal");
		//img_1.setVisibility(View.VISIBLE);
	}
	/**
	 * 字体处理
	 */
	TextPaint newPaint_name, newPaint_time, newPaint_say, newPaint_saybody;
	/**
	 * 各字体View
	 */
	TextView new_name_back, new_name, new_time_back, new_time, new_say_back,
				new_say;
	
	ArrayList<DataModel> arrayList = null;
	boolean loadListTaskFlag = false;
	String mUidString = null;
	AsyncTask<String, String, String> taskLoadList = null;
	AsyncTask<String, String, String> taskLoveLoadList = null;
	
	boolean localhasShow = false;
	public void getLocalListTask(){
		//mProgressDialog = new AlertDialog.Builder(PhotoFrameActivity.this, R.style.FullHeightDialog).
				//setView(view_progress).create();
		new AsyncTask<Object, Object, Object>(){

			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if (!localhasShow && loginDialog != null){
					loginDialog.show();
					localhasShow = true;
				}
				//array = new JSONArray();
//				mListJSON = new ArrayList<JSONObject>();
				mListJSON.clear();
			}

			@Override
			protected Object doInBackground(Object... params) {
				arrayList = ModelDataMgr.getInstance().getIdList(ModelDataMgr.PHOTO_ID_LIST);
				if (arrayList == null)
					arrayList = new ArrayList<DataModel>();
				
				int length = 0;
				length = arrayList.size();
				int i = 0;
				int index = 0;
				while (i < length){
					DataModel model;
					model =  (DataModel) ModelDataMgr.getInstance().getModel(arrayList.get(index).id,ModelDataMgr.PHOTO_DIR);
					if (model == null) {
						arrayList.remove(index);
					}
					else {
						if (((PhotoModel)model).id.contains("defaultID")){
							index ++;
						} else {
							if (((PhotoModel)model).photos != null && ((PhotoModel)model).photos.size() >= 1) {
								String url = ((PhotoModel)model).photos.get(0).url;
							
						
								String imgUrl = url;
								
				          		/*int endFlag = -1;
				          		int img_w = ((PhotoModel)model).photos.get(0).width;
				          		int img_h  =((PhotoModel)model).photos.get(0).height;
				          		endFlag = imgUrl.indexOf("!");
				          		
				          		if( ! imgUrl.contains(PublicInfo.picID_default_head))
			          			{
			          				imgUrl = imgUrl.substring(0, endFlag);
									if( img_w >= img_h )
									{
										imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_LARGE;
									}else
									{
										imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_HALF;
									}
			          			}*/
				          		
								File file = new File(LoadImageMgr.PIC_CACHE_PATH + LoadImageMgr.getInstance()
										.formatString(imgUrl));
								Log.v(MYTAG, "" + file.getName());
								if (file.exists()){
									index ++;
								} else {
									arrayList.remove(index);
								}
							}
						}
					}
					i ++;
				}
				if (arrayList.size() == 0){
					// 无图情况下，播放默认
					// 初始化默认
					DataModel object;
					ModelDataMgr.getInstance().initDefaultPic();
					for (i = 0; i < 4; i++) {
						object = new DataModel();
						object.id = PublicInfo.picID_defaults[i];
						object.uid ="";
						object.type = "photoid" ;
						arrayList.add(object);
					}
					// 一张图片都不符合显示条件
					/*nodataAlertDialog = new AlertDialog.Builder(PhotoFrameActivity.this).setMessage("目前没有可显示的照片，现在请您欣赏美图！").setNeutralButton("关闭", null).create();
					nodataAlertDialog.show();*/
					return null;
				}
				Log.v(MYTAG, "arrayList的长度为：" + arrayList.size());
				return null;
			}

			@Override
			protected void onPostExecute(Object result) {
				super.onPostExecute(result);
				Log.v(MYTAG, "arrayList的长度：" + arrayList.size());
				if(  arrayList.size() > 0 && arrayList.size() > mListJSON.size() )
				{
					//localLoadDetailTask(arrayList.get(array.length()));
					//loadDetailTask(arrayList.get(mListJSON.size()));
					//ModelDataMgr.getInstance().saveIdList(arrayList,ModelDataMgr.PHOTO_ID_LIST );
					loadDetailTask(arrayList.get(indexArrayList ++));
				}
			}
			
			
		}.execute("");
		
	}
	
	public void loadListTask(final boolean refresh, final int loadModel){
		if( refresh )
		{
			//array = new JSONArray();
//			mListJSON = new ArrayList<JSONObject>();
			mListJSON.clear();
			if( loadListTaskFlag )
			{
				return;
			}
				
		}
		taskLoadList = new AsyncTask<String, String, String>(){
			boolean taskRun = false;
			protected void onPreExecute() {
				if ( mUidString == null )
				{
					Componet uidComponet = UserInfoManager.getInstance(PhotoFrameActivity.this).getItem("uid");
					if( uidComponet != null )
					{
						mUidString = uidComponet.getValue();
					}
				}
				if( refresh )
				{
					loginDialog.show();
					loadListTaskFlag = true;
					// 避免过久的等待，网络中断等问题
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if(isDestryod)
							{
								return;
							}
							if (taskRun) {
								/*if (mProgressDialog.isShowing()) {
									mProgressDialog.dismiss();
								}*/
								if (loginDialog.isShowing())
									loginDialog.dismiss();
								taskLoadList.cancel(true);
								new AlertDialog.Builder(PhotoFrameActivity.this).setMessage("网络好像不给力！请选择？")
								.setNegativeButton("重置wifi网络", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										// 重置wifi
										Intent intent = new Intent();
										intent.putExtra("reset", true);
										intent.setClass(PhotoFrameActivity.this, WifiLoginActivity.class);
										startActivity(intent);
									}
								})
								.setPositiveButton("重试", new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										loadListTask(true, loadModel);
									}
								}).show().setCanceledOnTouchOutside(false);
							}
						}
					}, PublicInfo.MAX_TIME_WAITLAOD);
				}
			};
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				String page = "1";
				if( !refresh )
				{
//					page = arrayList.size()/PublicInfo.PER_LOAD + 1 + "";
					pageCount ++ ;
					page = pageCount + "";
				}
				if( refresh )
				{
					taskRun = true;//本地使用的时候
					
					pageCount = 1;
					page = pageCount + "";
				}
				String responString ;
//				Componet m_authComponet = UserInfoManager.getInstance(PhotoFrameActivity.this).getItem("m_auth");
				if ( null == m_auth ) {
					 return "";
				}
				String httpStr;
				if (loadModel == PLAYING_ALL) {
					httpStr = getResources().getString(R.string.http_feedlist);
					responString = NetHelper.getResponByHttpClient(httpStr,
							"photoid",page,m_auth);
				} else if (loadModel == PLAYING_LOVE) {
					httpStr = getResources().getString(R.string.http_lovelist);
					responString= NetHelper.getResponByHttpClient(httpStr,
							m_auth,page);
				} else {
					httpStr = getResources().getString(R.string.http_minelist);
					responString = NetHelper.getResponByHttpClient(httpStr,
							"photoid",page,m_auth);
				}
				
				if( refresh && responString != null && !responString.equals("") )
				{
					ModelDataMgr.getInstance().savePhotoListResponse(responString,1);//本地保存该列表
				}
				return responString;
			}
			protected void onPostExecute(String result) {
				loadListTaskFlag = false;
				taskRun = false;
				if( result != null && !result.equals("") )
				{
					if( refresh  )
					{
//						Toast.makeText(PhotoFrameActivity.this, "获取列表成功", Toast.LENGTH_SHORT).show();
						switchPlayModel = loadModel;
						currentPage = 0;
						arrayList.clear();
						update(result);
						return;
					}else
					{
						update(result);
					}
				}else {
					Toast.makeText(PhotoFrameActivity.this, "出错了，请检查你的网络！", Toast.LENGTH_SHORT).show();
					//mProgressDialog.dismiss();
					loginDialog.dismiss();
				}
			};
		}.execute("");
	}
	public static final int MSG_FIRST_CHECK = 999;
	public void setTimerRefresh()
	{
		checkVersion(MSG_FIRST_CHECK);
		new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					int count = 0;
					while(count < PublicInfo.REFRESH_TIME)
					{
						if (isDestryod) {
							return;
						}else
						{
							try {
								Thread.sleep(1000);
								count++;
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}
					//时间到
					if( mListJSON != null ){
						try {
							// 当前是否处于推送暂停状态
							while( play_stop && !mListJSON.get(currentPage).isNull("pushnoread"))
							{
								Thread.sleep(1000);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					// 开始调用刷新任务
					handler.sendEmptyMessage(0);
				}
			}).start();
	}
	
	public void switchModel(int pModel)
	{
		Intent intent = new Intent();
		intent.setClass(PhotoFrameActivity.this, PhotoFrameActivity.class);
		intent.putExtra("model", pModel);
		PhotoFrameActivity.this.startActivity(intent);
		PhotoFrameActivity.this.finish();
		isDestryod = true;
	}
	int indexArrayList = 0;
	private void update(String result)
	{
		try {
			JSONObject jsonObject = new JSONObject(result);
			if ( 0 == jsonObject.getInt("error") )
			{
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				int size = jsonArray.length();
				JSONObject temp;
				DataModel object ;
				if ( size == 0 && mListJSON.size() == 0 )
				{
					// 无图情况下，播放默认
					// 初始化默认
					ModelDataMgr.getInstance().initDefaultPic();
					for (int i = 0; i < 4; i++) {
						object = new DataModel();
						object.id = PublicInfo.picID_defaults[i];
						object.uid ="";
						object.type = "photoid" ;
						arrayList.add(object);
					}
					// 一张图片都不符合显示条件
					nodataAlertDialog = new AlertDialog.Builder(this).setMessage("目前没有可显示的照片，现在请您欣赏美图！").setNeutralButton("关闭", null).create();
					nodataAlertDialog.show();
				}else
				{
					for (int i = 0; i < size; i++) {
						temp = jsonArray.getJSONObject(i);
						object = new DataModel();
						object.id = temp.getString("id");
						object.uid = temp.getString("uid");
						object.type = temp.getString("idtype");
						arrayList.add(object);
					}
					c_sizeOfList = arrayList.size();
				}
			}
			
			if( arrayList.size() > 0 && arrayList.size() > indexArrayList  )
			{
				//2013.10.30PM 
				//loadDetailTask(arrayList.get(mListJSON.size()));
				loadDetailTask(arrayList.get(indexArrayList ++));
				ModelDataMgr.getInstance().saveIdList(arrayList,ModelDataMgr.PHOTO_ID_LIST );
			}else
			{
				/*if (mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
				}*/
				if (loginDialog.isShowing())
					loginDialog.dismiss();
//					Toast.makeText(PhotoFrameActivity.this, getResources().getString(R.string.dialog_msg_nomoredata), Toast.LENGTH_LONG).show();
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			/*if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}*/
			if (loginDialog.isShowing())
				loginDialog.dismiss();
//			Toast.makeText(PhotoFrameActivity.this, "error", Toast.LENGTH_LONG).show();
		}
	}
	public void loadDetailTask(final DataModel picJsonObject)
	{
		if( isDestryod )
		{
			return;
		}
		new AsyncTask<String, String, DataModel>(){
			boolean notopen = false;
			private boolean error = false;			// 读取操作中是否出错
			String typeidString = "photoid";
			String dirPath = null;
			String urlString = null;
			// @ze 2013.11.5
			boolean picExs   = true;
			String  picUrl   = null;
			
			protected void onPreExecute() {
				typeidString = picJsonObject.type;
				if ( typeidString.equals("photoid") || typeidString.equals("rephotoid")) {
					dirPath = ModelDataMgr.PHOTO_DIR;
					urlString = getResources().getString(R.string.http_photo_detail);
				}
			};
			@Override
			protected DataModel doInBackground(String... params) {
				// TODO Auto-generated method stub
				if (isDestryod) {
					return null;
				}
				if( notopen )
				{
					return null;
				}
				DataModel model = null;
				try {
				model =  (DataModel) ModelDataMgr.getInstance().getModel(picJsonObject.id,dirPath);
				if (uselocal){
					return model;
				}
				//如果是播放默认的时候执行的是model!= null
				if ( model == null && m_auth != null ) {
					String respon = NetHelper.getResponByHttpClient(urlString,
							picJsonObject.id,
							picJsonObject.uid,
							m_auth);
					JSONObject object;
					object = new JSONObject(respon);
					if ( 0 == object.getInt("error") ) {
//							model = new DataModel();
							object = object.getJSONObject("data");
							
							if ( typeidString.equals("photoid") || typeidString.equals("rephotoid")) {
								model = new PhotoModel();
								model.id 			= picJsonObject.id;
								model.uid 		= picJsonObject.uid;
								model.type		= picJsonObject.type;
								if( !object.isNull("name") )
								{
									((PhotoModel)model).name 	=  object.getString("name");
								}
								if( !object.isNull("dateline") )
								{
									((PhotoModel)model).time 	=  object.getString("dateline");
								}
								if( !object.isNull("tagname") )
								{
//									((PhotoModel)model).tagname 	=  object.getString("tagname");
									
								}
								if( !object.isNull("message") )
								{
									((PhotoModel)model).say 	=  object.getString("message");
									
								}
								if( !object.isNull("subject") )
								{
//									((PhotoModel)model).say 		=  object.getString("subject");
									((PhotoModel)model).tagname 		=  object.getString("subject");
								}
								if( !object.isNull("mylove") )
								{
//									((PhotoModel)model).say 		=  object.getString("subject");
									((PhotoModel)model).love 		=  object.getInt("mylove");
								}
								//语音相关字段
								if ( !object.isNull("soundurl") && !object.getString("soundurl").equals("")) {
									((PhotoModel)model).soundurl = object.getString("soundurl");
									try {
										((PhotoModel)model).soundFileName = ModelDataMgr.getInstance().downFile(((PhotoModel)model).soundurl, "");
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
//								 多图情况处理
								if( ! object.isNull("piclist"))
								{
									JSONArray picArray = object.getJSONArray("piclist");
									if( picArray == null || picArray.length() == 0 )
									{
										// piclist 为空
//										error = true;
										return null;
									}
									PicInfo picInfo;
									for (int i = 0; i < picArray.length(); i++) {
										if (isDestryod) {
											break;
										}
										if (i == 9)
											break;
										picInfo = new PicInfo();
										picInfo.url = picArray.getJSONObject(i).getString("pic");
										picInfo.height = Integer.parseInt( picArray.getJSONObject(i).getString("height") );
										picInfo.width 	=  Integer.parseInt( picArray.getJSONObject(i).getString("width") );
										
										/**
										 * 这里加入url后缀处理 
										 * By mouse 2013.10.30PM
										 */
										String imgUrl = picInfo.url;
										int endFlag = -1;
						          		int img_w = picInfo.width;
						          		int img_h  = picInfo.height;
						          		endFlag = imgUrl.indexOf("!");
						          		if ( endFlag != -1 || imgUrl.contains(PublicInfo.picID_default_head) )
						          		{
						          			if( ! imgUrl.contains(PublicInfo.picID_default_head))
						          			{
						          				imgUrl = imgUrl.substring(0, endFlag);
												if( img_w >= img_h )
												{
													//imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_LARGE;
												}else
												{
													imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_HALF;
												}
						          			}
											
						          		}
										picInfo.url = imgUrl;
						          		
										((PhotoModel)model).photos.add(picInfo
												);
										File drawableFile = new File(LoadImageMgr.PIC_CACHE_PATH + LoadImageMgr.getInstance().formatString( picInfo.url ) );
										if ( ! drawableFile.exists()) {
											LoadImageMgr.getInstance().loadImageFromUrl(picInfo.url);
											// @ze 2013.11.5
											/*picExs = false;
											picUrl = picInfo.url;*/
										}
										
									}
								}
							}
							ModelDataMgr.getInstance().saveModel(model,dirPath);
						}else
						{
							// 找不到该id的数据或者获取这个数据时出错了，得到的id得不到详情的内容 
							error = true;
						}
					
					}
				// 得到model
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					//mProgressDialog.dismiss();
					loginDialog.dismiss();
				}
				return model;
			}
			protected void onPostExecute(DataModel result) {
				if (isDestryod) {
					return;
				}
				/*if( ! picExs )
				{
					// 2013.11.5 @ze 
					LoadImageMgr.getInstance().loadDrawble
					(picUrl,null,null);
				}*/
				if( notopen )
				{
					return;
				}
				if ( ! error ) {
					if( result == null )
					{
						arrayList.remove(picJsonObject);
					}else
					{
						try {
							int n = ((PhotoModel)result).photos.size();
							for (int i = 0; i < n; i++) {
								JSONObject object = new JSONObject();
								ArrayList<PhotoModel.PicInfo> photo = new ArrayList<PhotoModel.PicInfo>();
								photo.add(((PhotoModel)result).photos.get(i));
								object.put("id", result.id);
								object.put("type", typeidString);
								object.put("fuid", result.fromUid);
								object.put("fname", result.fromName);
								object.put("love",  result.love);
								object.put("uid", result.uid);
								if( typeidString.equals("photoid") || typeidString.equals("rephotoid"))
								{
									object.put("imgarray", photo);
									if (((PhotoModel)result).say.equals("")) {
										object.put("say",  "no topic");
									}else {
										object.put("say",  ((PhotoModel)result).say);
									}
									
									object.put("listview", null);
									object.put("time",  ((PhotoModel)result).time);
									object.put("name",  ((PhotoModel)result).name);
									object.put("tagname",  ((PhotoModel)result).tagname);
									object.put("tagid",  ((PhotoModel)result).tagid);
									//语音相关字段
									object.put("soundurl", ((PhotoModel)result).soundurl);
									object.put("soundfilename", ((PhotoModel)result).soundFileName);
									object.put("soundtime", ((PhotoModel)result).soundtime);
								}
								//array.put(object);
								mListJSON.add(object);
								if (initFlag) {
									mviewAdapter.notifyDataSetChanged();
								}
								
							}
						
						/*JSONObject object = new JSONObject();
						
							object.put("id", result.id);
							object.put("type", typeidString);
							object.put("fuid", result.fromUid);
							object.put("fname", result.fromName);
							object.put("love",  result.love);
							object.put("uid", result.uid);
							if( typeidString.equals("photoid") || typeidString.equals("rephotoid"))
							{
								object.put("imgarray", ((PhotoModel)result).photos);
								object.put("say",  ((PhotoModel)result).say);
								object.put("listview", null);
								object.put("time",  ((PhotoModel)result).time);
								object.put("name",  ((PhotoModel)result).name);
								object.put("tagname",  ((PhotoModel)result).tagname);
								object.put("tagid",  ((PhotoModel)result).tagid);
							}
							//array.put(object);
							mListJSON.add(object);*/
							if( currentPage == 0 && !initFlag )
							{
								if( mListJSON.size() == 0 )
								{
									Toast.makeText(PhotoFrameActivity.this, "开始加载照片详情", Toast.LENGTH_SHORT).show();
								}
								if( mListJSON.size() > PublicInfo.FIRST_LOAD || 
										(  
												arrayList.size() > 1 && 
												mListJSON.size() > 1 	) ||
												arrayList.size() <= 1
										)
								{
									/*if (mProgressDialog != null && mProgressDialog.isShowing()) {
										mProgressDialog.dismiss();
									}*/
									if (loginDialog != null && loginDialog.isShowing())
										loginDialog.dismiss();
//									imgLoadingView.setVisibility(View.INVISIBLE);
//									layout_info_img.setVisibility(View.VISIBLE);
									//img_2.setVisibility(View.INVISIBLE);
									initFlag = true;
									resetPlayHandler();
									Log.v("mouse", "播放间隔5" + ";currentPage:" + currentPage);
//									showNext(currentPage,0);
									mviewAdapter.notifyDataSetChanged();
									if (!mListJSON.get(0).isNull("soundurl") && !mListJSON.get(0).getString("soundurl").equals("")) {
										playSoundBtn.setVisibility(View.VISIBLE);
									}
									if( model == PLAYING_ALL )
										setTimerRefresh();
									Log.v("test", "********** start to show! ***********");
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}else {
					JSONObject object = new JSONObject();
					try {
						object.put("id", "-1");
						object.put("type", "(((");
						object.put("say",  getResources().getString( R.string.notexist ));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//mProgressDialog.dismiss();
						loginDialog.dismiss();
					}
					//array.put(object);
					mListJSON.add(object);
					mviewAdapter.notifyDataSetChanged();
				}
				//2013.10.30PM
				
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (indexArrayList < arrayList.size()) {
							loadDetailTask(arrayList.get(indexArrayList ++));
						}
					}
				}, 1000);
				
				/*if ( mListJSON.size() < arrayList.size() ) {
					loadDetailTask(arrayList.get(mListJSON.size()));
				}*/
				
			}
		}.execute("");
	}
	private 	HandlerThread 	playThread;
	private 	Handler 		playHandler;
	ArrayList<Runnable> 		playRunnableList = null;
	private 	PlayRunnble 		playRun = null;
	public void initPlayHandle()
	{
		 // 
		playThread = new HandlerThread("play");
		playThread.start();
		playHandler = new Handler(playThread.getLooper());
		playRunnableList = new ArrayList<Runnable>();
	}
	public class PlayRunnble implements Runnable{
		int count;
		public boolean out;
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while( !out && count < PHOTO_SHOW_COUNT )
			{
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				count++;
			}
			// 无操作时间结束 开始进入播放模式
			if( !out )
				handler.sendEmptyMessage(99);
		}
	}
	public void resetPlayHandler()
	{
		if( mListJSON == null || mListJSON.size() == 0 || mListJSON.size() == 1)
		 {
			// 只有一张或者0不自动播放
			 return;
		 }
		removePlayThread();
		
		playRun = new PlayRunnble();
		playHandler.post(playRun);
	}
	public void removePlayThread()
	{
		if( playRun != null ){
			playRun.out = true;
			playHandler.removeCallbacks(playRun);
		}
	}
	public static final String SIZEMODEL_1 = "320";
	public static final String SIZEMODEL_2 = "512X768";
	AlertDialog nodataAlertDialog = null;
	public static int picNum = 1;
	
	int loadImgCount = 0;
	public boolean isLoadingPic = false;
	boolean firstShowFlag = false;	
	boolean hasAddFlag = false;
	boolean treamFlag = false;
	
	
	
	public boolean isDestryod = false;
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.v(TAG, "onDestroy");
		unregisterReceiver(wifiReceiver);
		
		isDestryod = true;
		for( int i = 0; i< pushRunnableList.size(); i++ )
		{
			if( pushRunnableList.get(i) != null )
			{
				networkHandler.removeCallbacks(pushRunnableList.get(i));
			}
			Log.v("test", "清除线程！");
		}
		pushRunnableList.clear();
		if (flagReceive) {
			unregisterReceiver(receiver);
			flagReceive = false;
		}
		if( wifiLock != null && wifiLock.isHeld() )
		{
			wifiLock.release();
		}
		if(mWakeLock != null && mWakeLock.isHeld() )
		{
			mWakeLock.release();
		}
		testFlag = false;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.v(TAG, "onResume");
		MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.v(TAG, "onPause");
		MobclickAgent.onPause(this);
		if (loginDialog != null) {
			loginDialog.dismiss();
		}
		if (exitDialog != null) {
			exitDialog.dismiss();
		}
		
	}
	private boolean muneShowFlag = false;
	public AnimationListener animationListener = new AnimationListener() {
		
		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub
			if ( animation == dismissAnimation  ) {
//				setPicInfo(null);
			}else if( animation == indexAnimation )
			{
				try {
					mViewPager.setVisibility(View.VISIBLE);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			animation_playing = true;
		}
		
		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			animation_playing = false;
			if( animation == menuOutAnimation )
			{
				menuView.setVisibility(View.INVISIBLE);
				love.setSelected(false);
				return;
			}else if( animation == menuInAnimation )
			{
				initLoveStatus();
				menuView.setVisibility(View.VISIBLE);
				return;
			}
			 if (animation == dismissAnimation || 
						animation == slideLeftAnimation ||
						animation == slideRightAnimation) {
				 Log.v("mouse", "播放间隔3" + ";currentPage:" + currentPage);
//				 showNext(currentPage,0);
				 mViewPager.setVisibility(View.INVISIBLE);
				 int toIndex = currentPage;
				 if (toIndex + 1 >= mListJSON.size() ) {
				 // @ mouse
					 if ( mListPushJSON.size() > 0) {
						 for (int i = 0; i < mListPushJSON.size(); i++) {
							mListJSON.remove(mListPushJSON.get(i));	
						}
						 mviewAdapter.notifyDataSetChanged();
						 mListPushJSON = new ArrayList<JSONObject>();
					}
					 
					toIndex = 0;
				 }else {
					toIndex ++;
				}
				// mViewPager.setCurrentItem(toIndex);
				 mViewPager.setCurrentItem(toIndex, false);
				 onpage(toIndex);
			 }else if( animation == indexAnimation )
				{
				 	ifPushData();
					resetPlayHandler();
				}
		}
	};
	public void onpage(int arg0)
	{
		try {
			currentPage = arg0;
			if( mViewPager.getVisibility() == View.INVISIBLE && indexAnimation != null )
			{
				mViewPager.startAnimation(indexAnimation);
			}
			if(  arg0 >= mListJSON.size() || mListJSON.get(arg0) == null )
			{
				arg0 = 0;
			}
//			mID 	= arrayList.get(arg0).id;
//			mType 	= arrayList.get(arg0).type;
//			initEventButton();
			initLoveStatus();
			mUidString = mListJSON.get(arg0).getString("uid");
//			isEventType(mType);
			if (mViewPager.getVisibility() == View.VISIBLE) {
				ifPushData();
			}
			
		
		Log.v(MYTAG, "page:" + arg0 + ";size:" + mListJSON.size());
		//倒数5张，加载新列表
		if( arrayList.size() > 5 && sizeOfList < c_sizeOfList
				&& mListJSON.get(arg0).getString("id").equals(arrayList.get(arrayList.size() - 5).id)  )
		{
			sizeOfList = c_sizeOfList;
			// 达到倒数第三张时，加载更多
			Log.v(MYTAG, "加载新列表！");
			loadListTask(false,model);
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	int sizeOfList = 0;
	int c_sizeOfList = 0;
	/**
	 * 是否需要唤醒屏幕
	 */
	public void ifAcque() {
		if (taskFlag){
			new AsyncTask<Object, Object, Object>(){

				@Override
				protected Object doInBackground(Object... params) {
					// TODO Auto-generated method stub
					int timeCount = 0;
					while (!pm.isScreenOn() || timeCount >= 10){
						taskFlag = false;
						PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
 						WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|
 								PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
 						wl.acquire(PublicInfo.ACQUIRE_MAX_TIME);
 						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
 						timeCount ++;
					}
					taskFlag = true;
					
					return null;
				}
				
			}.execute("");
		}
	}
	/**
	 * 判断是否是推送数据
	 */
	public void ifPushData() {
		try {
			if ( mListJSON!= null && mListJSON.size()-1 > currentPage && mListJSON.get(currentPage).optBoolean("pushnoread",false) )
			{
				mListJSON.get(currentPage).put("pushnoread", false);
				// 播放声音
				SoundPlayer.play(PhotoFrameActivity.this, R.raw.complete);
				stopOrContinue(true);
				// 如果屏幕是关闭的，打开屏幕
				//mWakeLock.acquire();//点亮 
				//By mouse点亮屏幕
				//修改点
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public void initLoveStatus()
	{
		try {
			if ( mListJSON != null && mListJSON.size() > currentPage ) {
				int set = mListJSON.get(currentPage).optInt("love", 0);
				if( set == 1 || model == PLAYING_LOVE ){
					love.setSelected(true);
				}else
				{
					love.setSelected(false);
				}
			}
	} catch (Exception e) {
		// TODO: handle exception
	}
	}
	public boolean play_stop = false;
	private boolean animation_playing = false;
	private boolean initFlag = false;
	public void stopOrContinue(boolean needStop)
	{
		if(  needStop )
		{
			play_stop = true;
			if (!muneShowFlag) {
				muneShowFlag = true;
				menuView.setVisibility(View.VISIBLE);
				menuView.startAnimation(menuInAnimation);
				// 2013.11.3
				photoFrameView.setVisibility(View.GONE);
			}
		}else
		{
			play_stop = false;
			if (muneShowFlag) {
				muneShowFlag = false;
				menuView.setVisibility(View.INVISIBLE);
				menuView.startAnimation(menuOutAnimation);
				// 2013.11.3
				photoFrameView.setVisibility(View.VISIBLE);
			}
		}
	}
	private static int PHOTO_SHOW_TIME = 5000;
	private static int PHOTO_SHOW_COUNT = 5;
	
	public boolean isNetAble()
	{
		// 网络是否可用
		 ConnectivityManager connectivityManager=(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
		 NetworkInfo net=connectivityManager.getActiveNetworkInfo();
		return net == null ? false : net.isConnected();
	}
	private Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			
			case 0:
				// 定时检查新版本，没新版本则刷新
				checkVersion(10086);
//				if( model == PLAYING_ALL )
//					switchModel(PLAYING_ALL);
//				else
//					switchModel(PLAYING_LOVE);
				break;
			case MSG_FIRST_CHECK :
				try {
					String cur_version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
					if ( ! cur_version .equals(msg.obj)) {
						Toast.makeText(PhotoFrameActivity.this, "发现新版本，开始下载！", Toast.LENGTH_LONG).show();
						download();
					}
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 10086:
				// check
				checkUpdate(msg);
				break;
			case 8080:
				Log.v("test", "线程间通信？！");
				DataModel result = (DataModel) msg.obj;
				try {
					JSONObject object = new JSONObject();
						object.put("id", result.id);
						object.put("type", result.type);
						object.put("fuid", result.fromUid);
						object.put("fname", result.fromName);
						object.put("love",  result.love);
						object.put("uid", result.uid);
						if( result.type.equals("photoid") || result.type.equals("rephotoid"))
						{
							object.put("imgarray", ((PhotoModel)result).photos);
							object.put("say",  ((PhotoModel)result).say);
							object.put("listview", null);
							object.put("time",  ((PhotoModel)result).time);
							object.put("name",  ((PhotoModel)result).name);
							object.put("tagname",  ((PhotoModel)result).tagname);
							object.put("tagid",  ((PhotoModel)result).tagid);
						}
						int pos = 0;
						if (currentPage + 1> mListJSON.size()-1) {
							pos = 0;
						}else
						{
							pos = currentPage + 1;
						}
						if( ! pm.isScreenOn() && play_stop )
						{
							// 屏幕关闭的
							stopOrContinue(false);
							
						}
						object.put("pushnoread", true);
						//array.put(pos,object);  //
						mListJSON.add(pos, object);
						// 2013.10.19 @ze
						// robin提出推送后第二轮循环时（本地循环）
						// 必须要把推送的图片放到正确的位置（推送过来即为数据最新的一张）
//						object.put("pushnoread", false);
//						array.put(0,object);
						// currentPage表示当前页面的页数要增加1 ？！
//						currentPage ++ ;//由于这些改动对多图横竖屏造成了影响，暂时先不改动
					} catch (Exception e) {
						e.printStackTrace();
					}
				break;
			case 8081:
					Log.v("test", "失败了重试？！");
					Toast.makeText(PhotoFrameActivity.this, "推送加载数据失败", Toast.LENGTH_LONG).show();
					//notifyPush((String)msg.obj);
				break;
			case 99:
				// 进入播放模式
				if( menuView.getVisibility() == View.VISIBLE )
				{
					resetPlayHandler();
				}else
				{
					mViewPager.startAnimation(dismissAnimation);
				}
				
				break;
			default:
				break;
			}
		};
	};
	public void checkUpdate(Message msg)
	{
		try {
			String cur_version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			if ( ! cur_version .equals(msg.obj)) {
				Toast.makeText(PhotoFrameActivity.this, "发现新版本，开始下载！", Toast.LENGTH_LONG).show();
				download();
			}else {
				// 没有新版本
				if( model == PLAYING_ALL )
					switchModel(PLAYING_ALL);
				else
					switchModel(PLAYING_LOVE);
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private Animation indexAnimation;
	private Animation slideLeftAnimation;	//2013.10.20
	private Animation slideRightAnimation;	//2013.10.20
	private Animation dismissAnimation;
	
	public int switchPlayModel = 0;
	public static final int CHANGE_TO_ALL = 1;
	public static final int CHANGE_TO_LOVE = 2;
	public static final int PLAYING_ALL = 22;
	public static final int PLAYING_LOVE = 11;
	public static final int PLAYING_MINE = 33;
	
	/**
	 * 
	 */
	public OnClickListener buttonClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			if( /*v == img_1 || v == img_2 || */v == photoFrameView )
			{
				MobclickAgent.onEvent(mContext, "ScreenClick");
				stopOrContinue(!play_stop);
			}
			else if( v == love || v == txt_love)
			{
				MobclickAgent.onEvent(mContext, "love");
				if (uselocal){
					//Toast.makeText(PhotoFrameActivity.this, "离线状态，操作失败！", Toast.LENGTH_SHORT).show();
					//localDialog.show();
					exitDialog.show();
					return;
				}
				else{
				try {
					if (mListJSON != null && mListJSON.size() > currentPage) {
						requsetSetLove(mListJSON.get(currentPage).getString("id"));
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				}
			}else if( v == playAll || v == txt_playAll)
			{
				MobclickAgent.onEvent(mContext, "refresh");
				
				//如果用户还未登录，要求用户先登录
				if (uselocal){
					//localDialog.show();
					exitDialog.show();
					return;
					
				} else {
					switchModel(PLAYING_ALL);
				}
			}else if( v == playLove || v == txt_playLove)
			{
				MobclickAgent.onEvent(mContext, "see_collect");
				if (uselocal){
					//localDialog.show();
					exitDialog.show();
					return;
				}
				switchModel(PLAYING_LOVE);
			}else if(v == playMine || v == txt_playMine)
			{
				if (uselocal){
					//localDialog.show();
					exitDialog.show();
					return;
				}
				switchModel(PLAYING_MINE);
			}
			/*else if( v == deleteView ) 
			{
				// 屏蔽删除功能
//				if ( animation_playing ) {
//					return;
//				}else
//				{
////					array.
//					try {
//						array.getJSONObject(currentPage).put("delete", true);
//						img_1.startAnimation(deleteOutAnimation);
//					} catch (Exception e) {
//					}
//				}
			}*/else if( v == logoutView || v == txt_logout)
			{
				MobclickAgent.onEvent(mContext, "exit");
				if (uselocal){
					//localDialog.show();
					exitDialog.show();
					return;
				} else {
					exitDialog.show();
				}
				
			}else if( v == checkButtonView )
			{
				checkcount++;
				if (checkcount == 5) {
					debug();
					checkcount = 0;
				}
			}else if( v == btn_progress )
			{
				//mProgressDialog.dismiss();
				loginDialog.dismiss();
			}else if (v == ED_cancelBtn) {
				if (uselocal) {
					exitDialog.dismiss();
					Intent intent = new Intent(PhotoFrameActivity.this, MainActivity.class);
					startActivity(intent);
					PhotoFrameActivity.this.finish();
					return;
				}
				exitDialog.dismiss();
			}else if (v == ED_OKBtn) {
				if (uselocal) {
					exitDialog.dismiss();
					return;
				}
				Componet uidComponet = UserInfoManager.getInstance(PhotoFrameActivity.this).getItem("uid");
				if (uidComponet != null) {
					FamilyDayVerPMApplication.unBindJpush(PhotoFrameActivity.this, uidComponet.getValue());
					Componet userComponet = UserInfoManager.getInstance(PhotoFrameActivity.this).getItem("username");
					UserInfoManager.getInstance(PhotoFrameActivity.this).deleteAll();
					if ( userComponet != null ) {
						UserInfoManager.getInstance(PhotoFrameActivity.this).save(userComponet);
						UserInfoManager.getInstance(PhotoFrameActivity.this).add(userComponet);
					}
					Intent intent = new Intent();
					intent.setClass(PhotoFrameActivity.this, MainActivity.class);
					startActivity(intent);
					PhotoFrameActivity.this.finish();
//					unregisterReceiver(receiver);
				} else {
					Intent intent = new Intent();
					intent.setClass(PhotoFrameActivity.this, MainActivity.class);
					startActivity(intent);
					PhotoFrameActivity.this.finish();
				}
			}else if (v == BD_btn) {
				batteryDialog.dismiss();
			}
				
			else if (v == playSoundBtn) {
				if (!soundTipsRlFlag) {
					soundTipsRlFlag = true;
					SharedPreferences soundPreferences = 
							getSharedPreferences("update.config", Activity.MODE_WORLD_READABLE);
					Editor editor = soundPreferences.edit();
					editor.putBoolean("soundTipsRl", true);
					editor.commit();
					tipsRl.setVisibility(View.VISIBLE);
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							if (tipsRl.getVisibility() == View.VISIBLE) {
								tipsRl.setVisibility(View.GONE);
							}
						}
					}, 3000);
				}
				
				if (!playSoundBtn.isSelected()) {
					playSoundBtn.setSelected(true);
					playSoundBtn.setBackgroundResource(R.drawable.audio_pause_btn_sel);
					/*SoundPlayStop.getInstance().start(Environment.getExternalStorageDirectory()
							.getAbsolutePath()
							+ "/familydayVerPm/sounddata/1015_13932240902sZT.amr");*/
					int arg0 = mViewPager.getCurrentItem();
					try {
						final JSONObject object = mListJSON.get(arg0);
						if (!object.isNull("soundurl") && !object.getString("soundurl").equals("")) {
							String soundfilename = object.getString("soundfilename");
							float soundtime = 0;
							if (!object.isNull("soundtime")) {
								try {
									soundtime = Float.parseFloat(object.getString("soundtime"));
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							File file = new File(soundfilename);
							if (file.exists()) {
								SoundPlayStop.getInstance().start(soundfilename, soundtime);
							}else {
								SoundPlayStop.getInstance().start(object.getString("soundurl"), soundtime);
								executorService.submit(new Runnable() {
									@Override
									public void run() {
										try {
											ModelDataMgr.getInstance().downFile(object.getString("soundurl"), "");
										} catch (JSONException e) {
											e.printStackTrace();
										}
									}
								});
							}
						}
						//SoundPlayStop.getInstance().start(mListJSON.get(arg0).getString("soundurl"));
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
				}else {
					SoundPlayStop.getInstance().stop();
					//playSoundBtn.setSelected(false);
					//playSoundBtn.setBackgroundResource(R.drawable.audio_play_btn_sel);
				}
				
			}
			// TODO Auto-generated method stub
		}
	};
	private EditText debugEditText;
	public void debug()
	{
		debugEditText = new EditText(this);
		new AlertDialog.Builder(this).setView(debugEditText).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String str_debug = debugEditText.getText().toString();
				Intent intent = null;
//				startActivity(wifiSettingsIntent);
				if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_TIME))
				{
					intent= new Intent(android.provider.Settings.ACTION_DATE_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_SOUND) )
				{
					intent= new Intent(android.provider.Settings.ACTION_SOUND_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_WIFI) )
				{
					intent= new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_SETTING) )
				{
					intent= new Intent(android.provider.Settings.ACTION_SETTINGS);
					startActivity(intent);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_VERSION) )
				{
					checkVersion(10086);
				}else if( str_debug.equalsIgnoreCase(PublicInfo.DEBUG_VERCOD) )
				{
					ToastUtil.show(PhotoFrameActivity.this, updateTools.GetVersion(PhotoFrameActivity.this));
				}
					
			}
		}).setTitle("Welcome to DebugModel !").create().show();
	}
	
	public void deletePlayingPhoto()
	{
		// 删除当前照片：动画->移除->取消暂停状态
		if ( animation_playing ) {
			return;
		}else
		{
			try {
				mListJSON.get(currentPage).put("delete", true);
				if (model == PLAYING_LOVE)
					//img_1.startAnimation(deleteOutAnimation);
				if(muneShowFlag && model == PLAYING_LOVE)
				{
					stopOrContinue(false);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	int checkcount = 0;
	public void requsetSetLove(final String mid)
	{
		if( m_auth == null )
		{
			return;
		}
		new AsyncTask<String, String, String>(){
				@Override
				protected void onPreExecute() {
					// TODO Auto-generated method stub
					super.onPreExecute();
					if( love.isSelected() )
					{
						deletePlayingPhoto();
					}
					love.setSelected( ! love.isSelected() );
					love.setTag("1");
				}
				@Override
				protected String doInBackground(
						String... params) {
					// TODO Auto-generated method stub
					String respon = null;
					try {
						 respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_set_love), 
								mListJSON.get(currentPage).getString("id"), 
								mListJSON.get(currentPage).getString("type"), 
								(love.isSelected() ? "1" : "0"),m_auth);
					} catch (NotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return respon;
				}
				@Override
				protected void onPostExecute(String result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					love.setTag("0");
					if( result == null )
					{
						return;
					}
					try {
						JSONObject object = new JSONObject(result);
						if( object.getInt("error") == 0)
						{
							String dirname  = ModelDataMgr.PHOTO_DIR;
							String idString  = mid;
							DataModel currentDataModel = (DataModel) ModelDataMgr.getInstance().getModel(idString, dirname);
							currentDataModel.love = (love.isSelected() ? 1 : 0 );
							ModelDataMgr.getInstance().saveModel(currentDataModel, dirname);
							mListJSON.get(currentPage).put("love", currentDataModel.love );
							if (love.isSelected()) {
//								Toast.makeText(PhotoFrameActivity.this, "收藏成功！", Toast.LENGTH_SHORT).show();
							}else
							{
//								Toast.makeText(PhotoFrameActivity.this, "取消收藏成功！", Toast.LENGTH_SHORT).show();
							}
							
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}.execute("");
	}
public ImageCallBack imageCallBack = new ImageCallBack() {
		
		@Override
		public void setImage(Drawable d, String url, final ImageView view) {
			// TODO Auto-generated method stub
			if( /*mActiveImages.contains(view) &&*/ url.equals((String)view.getTag()))
			{
				//img_2.setVisibility(View.INVISIBLE);
				view.setImageDrawable(d);
				if( isLoadingPic )
				{
					//view.startAnimation(indexAnimation);
					handler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if(isDestryod)
							{
								return;
							}
							if( view.getDrawable() != null)
								isLoadingPic = false;
						}
					}, PHOTO_SHOW_TIME);
				}
			}
		}
	};
	public AlertDialog netErrorDialog = null;
	public void notifyWifiChange()
	{
		if( uselocal )
		{
			return;
		}
		// 网络断开
		if( isNetAble() )
		{
			if( netErrorDialog != null && netErrorDialog.isShowing() )
			{
				netErrorDialog.hide();
			}
			return;
		}else
		{
			if( netErrorDialog == null )
			{
				netErrorDialog = new AlertDialog.Builder(this).setMessage("请设置wifi，以链接网络！").setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						openWifiLogin();
					}
				}).
				setNegativeButton("离线使用", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						uselocal = true;
						Intent localIntent = new Intent(PhotoFrameActivity.this, PhotoFrameActivity.class);
						localIntent.putExtra("uselocal", true);
						startActivity(localIntent);
						PhotoFrameActivity.this.finish();
					}
				}).create();
			}
			netErrorDialog.setCanceledOnTouchOutside(false);
			netErrorDialog.show();
		}
	}
	public void logErrorImgInfo(int index)
	{
//		array.getJSONObject(index);
	}
	public void openWifiLogin()
	{
		Intent intent = new Intent();
		intent.setClass(PhotoFrameActivity.this, WifiLoginActivity.class);
		startActivity(intent);
	}
	public void download()
	{
		downProgressBar = new ProgressDialog(this);
		updateTools = new UpdateTools(callback, getResources().getString(R.string.http_update) 
				/*"http://familydayverpm.googlecode.com/files/familyCube1.apk"*/
					, ModelDataMgr.CUBE_FILE_DIR, "cube.apk");
		updateTools.download(this, updateTools.handler);
		downProgressBar.setMessage("更新中...");
		downProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downProgressBar.show();
	}
	UpdateTools updateTools;
	DownloadCallback callback = new DownloadCallback() {
		
		@Override
		public void updateDownloadProgress(int cur_size) {
			// TODO Auto-generated method stub
			downProgressBar.setMax(updateTools.fileSize);
			downProgressBar.setProgress(cur_size);
		}
		
		@Override
		public void notifyDownError() {
			// TODO Auto-generated method stub
			downProgressBar.hide();
			Toast.makeText(PhotoFrameActivity.this, "下载出错!", Toast.LENGTH_SHORT).show();
		}
		
		@Override
		public void finishDownload() {
			// TODO Auto-generated method stub
			
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setAction("android.intent.action.VIEW.INSTALL");
			intent.setDataAndType(Uri.fromFile(new File( ModelDataMgr.CUBE_FILE_DIR + "cube.apk") ),
			                                "application/vnd.android.package-archive");

			startActivity(intent);
			

		}
	};
	ProgressDialog downProgressBar;
	
	public void checkVersion( final int what )
	{
		// 2013 10 19 添加新参数 用于标志首次切换进入播放时的检测版本
		new Thread( new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_updatecheck));
				try {
					if (respon != null  && !respon.equals("")) {
						JSONObject object = new JSONObject(respon);
						if (object.getInt("error") == 0 ) {
							object = object.getJSONObject("data");
							String version = object.getString("version");
//							Message msg = handler.obtainMessage(10086);
							Message msg = handler.obtainMessage(what);
							msg.obj = version;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}).start();
	}
	
	
	
	/**
	 * wifi信号的监听 
	 * By mouse
	 */
	BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
			//获得网络连接服务   
		    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);   
		    // State state = connManager.getActiveNetworkInfo().getState();   
		    // 获取WIFI网络连接状态  
		    State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();   
		    // 判断是否正在使用WIFI网络   
		    if (State.CONNECTED == state) {
		    	Log.v(TAG, "WIFI网络");
		    	new Handler().post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						//wifiView.setBackgroundResource(R.drawable.menu_wifi_on);
					}
				});
		    	
		    } else {
		    	Log.v(TAG, "没有WIFi网络");
		    	new Handler().post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						//wifiView.setBackgroundResource(R.drawable.menu_wifi_1);
					}
				});
		    }
			}else if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
				int type = intent.getIntExtra("plugged", -1);
				MainActivity.lastPlugged = MainActivity.currentPlugged;
				MainActivity.currentPlugged = type;
				if (MainActivity.lastPlugged != MainActivity.currentPlugged)
					MainActivity.isFirstFull = false;
				Log.v(TAG, "充电类型：" + type);
				int level = intent.getIntExtra("level", -1);
				int scale = intent.getIntExtra("scale", -1);
				if (level >= 0 && scale > 0)
					currentLevel = (level * 100) / scale;
				if (batteryDialog != null && batteryDialog.isShowing())
					batteryDialog.dismiss();
				
				if (type == 1 && currentLevel >= 100 && !MainActivity.isFirstFull){
					MainActivity.isFirstFull = true;
					//batteryDialog.setMessage("充电已完成！");
					BD_notice.setText("charging has finished!");
					batteryDialog.show();
				} else if (type == 1 && MainActivity.lastPlugged != MainActivity.currentPlugged) {
					//batteryDialog.setMessage("正在充电！当前电量：" + currentLevel + "%");
					BD_notice.setText("battery：" + currentLevel + "%");
					batteryDialog.show();
				}
			}
		}
	};
	
	boolean taskFlag = true;
	/**
	 *  Date		: 2013.10.19
	 *  Author		: @ze
	 *  Action 		: 增加滑屏动作
	 *  
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return super.onTouchEvent(event);
	}
	/**
	 * By mouse robin哥要求切图不要拉太久
	 */
	private static float MIN_TOUCH_CHANGE = 30.0f;
	
	public OnTouchListener onTouchListener = new OnTouchListener() {
		public float 			down_x = 0 ;
		public float 			up_x = 0;
		
		public float 			abs_down_x = 0 ;
		public float 			abs_up_x = 0;
		
		public float 			temp_x = 0;
		
		public int 			down_l = 0;
		public int 			down_r = 0;
		
//		private int 			down_t = 0;
		
//		private int 			down_b = 0;
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
//			if( v == img_1 || v == photoFrameView || v == rootView )
			{
				if ( event.getAction() == MotionEvent.ACTION_DOWN ) {
					down_x = event.getX();
					abs_down_x = event.getRawX();
					temp_x = down_x;
					down_l = v.getLeft();
					down_r = v.getRight();
				}else if ( play_stop &&  event.getAction() == MotionEvent.ACTION_MOVE ) {
					// 动画效果
					float cur_x = event.getX();
					if( currentPage == 0 && (int)(v.getLeft() + (cur_x - down_x) ) > 0 )
					{
						
					}else {
						v.layout( (int)(v.getLeft() + (cur_x - down_x) ),
								v.getTop(), 
								(int) ( v.getRight()   + (cur_x - down_x) ),
								v.getBottom());
					}
					temp_x = cur_x;
				}else if ( event.getAction() == MotionEvent.ACTION_UP ) {
					up_x = event.getX();
					abs_up_x = event.getRawX();
					Log.v("getx","" +  event.getRawX());
					if(  Math.abs( abs_down_x - abs_up_x) >= MIN_TOUCH_CHANGE &&  play_stop )
					{
						if( abs_down_x > abs_up_x )
						{
							// next
							currentPage ++;
							v.startAnimation(slideLeftAnimation);
						}else
						{
							// previous
							if( currentPage > 0 )
							{
								currentPage --;
								v.startAnimation(slideRightAnimation);
								
								
							}
							
						}
						
					}else {
						v.layout( down_l,
								v.getTop(), 
								down_r,
								v.getBottom());
						if( Math.abs( abs_down_x - abs_up_x) < 10 )
						{
							MobclickAgent.onEvent(mContext, "ScreenClick");
							stopOrContinue(!play_stop);
						}
						
					}
				}
			}
			return true;
		}
	};
	
	int posJsonArray = 0;
	int temp_pos = 0;
	/**
	 * By mouse
	 * 拉取到新数据的处理
	 * @author mouse 2013.10.24修复 推送顺序问题
	 */
	JSONArray pushArray = new JSONArray();
	public void notifyPull(final JSONArray jsonArray){
		MobclickAgent.onEvent(mContext, "rec_pic");//收到推送
		new AsyncTask<Object, Object, DataModel>(){
			// @ze 2013.11.5
			boolean picExs   = true;
			String  picUrl   = null;
			@Override
			protected DataModel doInBackground(Object... params) {
				// TODO Auto-generated method stub
				
				try {
						
					JSONObject extraObject = jsonArray.getJSONObject(posJsonArray ++);
				    final String pushType 	= extraObject.optString("idtype");
				    final String uid				= extraObject.optString("uid");
				    final String id					= extraObject.optString("id");
				    
				    DataModel photoModel = null;

					if( m_auth == null )
						return null;
					String respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_photo_detail),
							id,
							uid,
							m_auth);
					JSONObject object;
					try {
						object = new JSONObject(respon);
					if ( 0 == object.getInt("error") ) {
//							model = new DataModel();
							object = object.getJSONObject("data");
								photoModel = new PhotoModel();
								photoModel.id 			= id;
								photoModel.uid 		= uid;
								photoModel.type		= pushType;
								if( !object.isNull("name") )
								{
									((PhotoModel)photoModel).name 	=  object.getString("name");
								}
								if( !object.isNull("dateline") )
								{
									((PhotoModel)photoModel).time 	=  object.getString("dateline");
								}
								if( !object.isNull("message") )
								{
									((PhotoModel)photoModel).say 	=  object.getString("message");
								}
								if( !object.isNull("subject") )
								{
									((PhotoModel)photoModel).tagname 		=  object.getString("subject");
								}
								if( !object.isNull("mylove") )
								{
									((PhotoModel)photoModel).love 		=  object.getInt("mylove");
								}
								//增加声音保存的字段
								if ( !object.isNull("soundurl") && !object.getString("soundurl").equals("")) {
									((PhotoModel)photoModel).soundurl = object.getString("soundurl");
									try {
										((PhotoModel)photoModel).soundFileName = ModelDataMgr.getInstance().downFile(((PhotoModel)photoModel).soundurl, "");
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
//								 多图情况处理
								if( ! object.isNull("piclist"))
								{
									JSONArray picArray = object.getJSONArray("piclist");
									PicInfo picInfo;
									for (int i = 0; i <picArray.length(); i++) {	// 相框暂时支持多图时一张图片
										if (i >= 9)
											break;
										picInfo = new PicInfo();
										picInfo.url = picArray.getJSONObject(i).getString("pic");
										picInfo.height = Integer.parseInt( picArray.getJSONObject(i).getString("height") );
										picInfo.width 	=  Integer.parseInt( picArray.getJSONObject(i).getString("width") );
										
										String imgUrl = picInfo.url;
										int endFlag = -1;
						          		int img_w = picInfo.width;
						          		int img_h  = picInfo.height;
						          		endFlag = imgUrl.indexOf("!");
						          		if ( endFlag != -1 || imgUrl.contains(PublicInfo.picID_default_head) )
						          		{
						          			if( ! imgUrl.contains(PublicInfo.picID_default_head))
						          			{
						          				imgUrl = imgUrl.substring(0, endFlag);
												if( img_w >= img_h )
												{
													imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_LARGE;
												}else
												{
													imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_HALF;
												}
						          			}
											
						          		}
										picInfo.url = imgUrl;
										
										
										((PhotoModel)photoModel).photos.add(picInfo
												);
										File drawableFile = new File(LoadImageMgr.PIC_CACHE_PATH + LoadImageMgr.getInstance().formatString( picInfo.url ) );
										if ( ! drawableFile.exists()) {
//											LoadImageMgr.getInstance().loadImageFromUrl(picInfo.url);
											// @ze 2013.11.5
											picExs = false;
											picUrl = picInfo.url;
										}
									}
								}
							}
							ModelDataMgr.getInstance().saveModel(photoModel,ModelDataMgr.PHOTO_DIR);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return photoModel;
				
				} catch (JSONException e) {
				// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return null;
			}
			
			@Override
			protected void onPostExecute(DataModel result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null) {
					try {
						if( ! picExs )
						{
							// 2013.11.5 @ze 
							LoadImageMgr.getInstance().loadDrawble
							(picUrl,null,null);
						}
						/**
						 * By mouse 2013.10.31PM
						 */
						int n = ((PhotoModel)result).photos.size();
						for (int j = n - 1; j >= 0; j--) {
							ArrayList<PhotoModel.PicInfo> photo = new ArrayList<PhotoModel.PicInfo>();
							photo.add(((PhotoModel)result).photos.get(j));
							
						JSONObject [] object = new JSONObject[2];
						for (int i = 0; i < object.length; i++) {
							object[i] = new JSONObject();
							object[i].put("id", result.id);
							object[i].put("type", result.type);
							object[i].put("fuid", result.fromUid);
							object[i].put("fname", result.fromName);
							object[i].put("love",  result.love);
							object[i].put("uid", result.uid);
							if( result.type.equals("photoid") || result.type.equals("rephotoid"))
							{
								object[i].put("imgarray", photo);
								object[i].put("say",  ((PhotoModel)result).say);
								object[i].put("listview", null);
								object[i].put("time",  ((PhotoModel)result).time);
								object[i].put("name",  ((PhotoModel)result).name);
								object[i].put("tagname",  ((PhotoModel)result).tagname);
								object[i].put("tagid",  ((PhotoModel)result).tagid);
								//增加语音
								object[i].put("soundurl", ((PhotoModel)result).soundurl);
								object[i].put("soundfilename", ((PhotoModel)result).soundFileName);
								object[i].put("soundtime", ((PhotoModel)result).soundtime);
							}
						}
							
							/*if (mViewPager.getCurrentItem() + 1 >= mListJSON.size()) {
								pos = 0;
							}else
							{
								pos = mViewPager.getCurrentItem() + 1;
							}*/
							if( ! pm.isScreenOn() && play_stop )
							{
								// 屏幕关闭的
								stopOrContinue(false);
								
							}
							object[0].put("pushnoread", true);
							mListTrueObjects.add(object[0]);
							mListPushJSON.add(object[0]);
							
							//2013.10.24PM
							object[1].put("pushnoread", false);
							mListFalseObjects.add(object[1]);
							
							//currentPage ++;
							//array.put(0,object);
							
						}
						int pos = mViewPager.getCurrentItem() + 1;
						for (int i = 0; i < mListTrueObjects.size(); i++) {
							mListJSON.add(pos, mListTrueObjects.get(i));
						}
						for (int i = 0; i < mListFalseObjects.size(); i++) {
							mListJSON.add(0, mListFalseObjects.get(i));
						}
						if (mListTrueObjects.size() > 0 || mListFalseObjects.size() > 0) {
							mviewAdapter.notifyDataSetChanged();
						}
						mListFalseObjects = new ArrayList<JSONObject>();
						mListTrueObjects = new ArrayList<JSONObject>();
						
						ifAcque();
						Log.v(PullImageService.TAG, "加载第" + posJsonArray + "张新图片;插入位置：" + temp_pos);
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
				} else {
					Toast.makeText(PhotoFrameActivity.this, "新图片加载失败", 1000).show();
				}
				
				if (posJsonArray < jsonArray.length()) {
					notifyPull(jsonArray);
				}
				else
					posJsonArray = 0;
			}
			
		}.execute("");
	}
	List<JSONObject> mListFalseObjects = new ArrayList<JSONObject>();
	List<JSONObject> mListTrueObjects = new ArrayList<JSONObject>();
	List<JSONObject> mListPushJSON = new ArrayList<JSONObject>();
	boolean isPalyPushPic = false;
	int posPushArray = 0;
}
